<template>
  <el-dialog width="800px" class="approveDialog" :visible.sync="show" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
    <span slot="title">
      <i class="iconfont icon-a-wenjian1"></i>
      <span>各季度奖惩情况</span>
    </span>
    <div class="operate_wrap" style="margin-top: 20px">
      <div class="flex-center">
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="showDetailDialog('build')" style="margin-bottom: 10px;"><i class="iconfont icon-jiahao"></i>新增</el-button>
      </div>

      <div class="flex-right">

      </div>
    </div>
    <div class="list_wrap">
      <el-table style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px;" :data="list[0]">
        <!--                class=""-->
        <!--                      :border="$store.getters.getTheme('tableBorder')"-->
        <!--                      :row-style="$store.getters.getTheme('tableRowStyle')"-->
        <!--                      :cell-style="$store.getters.getTheme('tableCellStyle')"-->
        <!--                      :header-cell-style="$store.getters.getTheme('tableHeaderCellStyle')"-->
        <!--                      :stripe="$store.getters.getTheme('tableStripe')" ref="multipleTable" :data="list[0]" tooltip-effect="dark"-->
        <!--                      @cell-click="cellClick" -->

        <!--                      @selection-change="handleSelectionChange" -->
        <!--          >-->
        <!--                <el-table-column show-overflow-tooltip label="序号" type="index" width="60">-->
        <!--                    <template slot-scope="scope">-->
        <!--                        <span>{{ search.pageIndex * search.pageSize + scope.row.listIndex + 1 }}</span>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <el-table-column show-overflow-tooltip label="标题" prop="title" min-width="12%">
        </el-table-column>
        <el-table-column show-overflow-tooltip label="日期" prop="date" min-width="12%">
          <template slot-scope="scope">
            <span>{{ timeFormat(scope.row.date) }}</span>
          </template>
        </el-table-column>
        <!--                <el-table-column show-overflow-tooltip label="备注" prop="remark" min-width="25%"></el-table-column>-->
        <!--                <el-table-column label="附件" prop="file" min-width="12%">-->
        <!--                    <template slot-scope="scope">-->
        <!--                        <div style="display: flex; justify-content: center"><img @click.stop="showFiles(scope.row, '文件')" style="width: 20px; cursor: pointer;" src='@/assets/images/file.png' alt=''></div>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <el-table-column width="250" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="handleClickDeal({type:'show',name:'查看',detailId:scope.row.id})">&nbsp;查看</el-button>
            <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="handleClickDeal({type:'update',name:'修改',detailId:scope.row.id})">&nbsp;修改</el-button>
            <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="handleClickDeal({type:'delete',name:'删除',detailId:scope.row.id})">&nbsp;删除</el-button>

          </template>
        </el-table-column>
      </el-table>

    </div>
    <div slot="footer" class="dialog-footer">
      <!--新建和编辑的暂存上报-->
      <!--            <el-button size="small" @click="showFileDialog=false"><i class="iconfont icon-icon_cancel"></i> 关 闭-->
      <!--            </el-button>-->
    </div>
    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
  </el-dialog>
</template>

<script>

export default {
  name: "quarter-award-manage",
  components: {
    Detail: require('./quarter-award-detail/quarter-award-detail.vue').default
  },
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  data() {
    let permissionBaseCode = "1000114";
    return {

      permission: {
        add: ['100', `${permissionBaseCode}:add`],
        show: ['100', `${permissionBaseCode}:show`],
        edit: ['100', `${permissionBaseCode}:edit`],
        del: ['100', `${permissionBaseCode}:del`],
        // listPage: ['100', `${permissionBaseCode}:listPage`],
      },
      // formShow: false,//二维码弹窗显影
      projectUrl: '',
      addCan: false,//是否有新增权限
      contract_id: '',
      selectFile: '',
      fileOptions: [],
      allowAdd: false,
      title: "铁路监测系统",
      // 搜索参数
      search: {
        searchName: '',
        pageIndex: 0,
        pageSize: 10,
        pageSum: 0,
        searchType: '',
        contractId: '',
        flowShowName: '',
        dateHandover: '',

        searchTime: '',//日期
        searchTimes: '',//日期
      },
      // 列类型表
      list: [],

      typeOptions: [

      ],
      // 已经选择的列表id
      selectedIds: [],
      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeNmae: '新增'
      },
      //  选择的施工合同
      contractId: [],
      // el的table列表
      elTableList: [
        {
          name: '日期',
          prop: 'title',
          width: '12%',
        },
        {
          name: '内容',
          prop: 'remark',
          width: '30%',
        },
        {
          name: '登记人',
          prop: 'registerUser',
          width: '10%',
        },
        {
          name: '登记时间',
          prop: 'registerDate',
          width: '12%',
        },
      ],
      fileTitle: '文件',
      nowFileList: [],
      showFileDialog: false,
      fileSystem: {
        attachId: '',
        sys: 'riskSafetyEducation',
        module: 'riskSafetyEducation',
        part: ['one'],
      },
      show: false
    }
  },
  watch: {
    value() {
      this.show = this.value
    },
    show(newVal) {
      this.$emit('input', newVal)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    timeFormat(Date, fmt = 'yyyy-MM-dd') {
      // "yyyy-MM-dd hh:mm:ss.S" ==> 2006-07-02 08:09:04.423
      // "yyyy年M-d h:m:s.S"      ==> 2006年7-2 8:9:4.18
      if (typeof Date === 'string') {
        Date = new window.Date(Date.replace(/-/g, '/'));
      }
      if (!(Date instanceof window.Date)) {
        console.log('时间格式化失败');
        return '';
      }
      const o = {
        'M+': Date.getMonth() + 1,
        'd+': Date.getDate(),
        'h+': Date.getHours(),
        'm+': Date.getMinutes(),
        's+': Date.getSeconds(),
        'q+': Math.floor((Date.getMonth() + 3) / 3)
        // 'S': Date.getMilliseconds()
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (Date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
      }
      return fmt;
    },
    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        // if(!isNaN(result)){
        //     return this.$publicJs.exchangeKuaiJi(result)
        // }
        return result
      }
    },

    /**
     * 获取标段下属
     **/
    seledContract(val) {
      let obj = {};
      obj = this.fileOptions.find((item) => {
        return item.id === val;
      });
      this.companyId = obj.id
      //this.gettree(obj)
      //this.demo(obj)
      this.getList()
    },



    // 点击单元格 任务名称展示详情
    cellClick(row, column, cell, event) {
      // console.log(row, column, cell, event)
      console.log(column)
      if (column.property === 'title') {
        this.handleClickDeal({
          type: 'show',
          detailId: row.id,
          actions: row.actions,
        })
      }
    },
    resset() {
      this.search = {
        searchName: '',
        pageIndex: 0,
        pageSize: 10,
        pageSum: 0,
        searchType: '',
        contractId: '',
        flowShowName: '',
        dateHandover: '',

        searchTime: '',//日期
        searchTimes: '',//日期
      }
    },
    // 获取列表 api
    getList(reload) {

      if (this.search.hasOwnProperty('dateHandover')) {
        if (this.search.dateHandover != null) {
          this.search.searchTime = this.search.dateHandover[0]
          this.search.searchTimes = this.search.dateHandover[1]
        } else {
          this.search.searchTime = null
          this.search.searchTimes = null
        }
      }

      if (reload) {
        this.search.pageIndex = 0
      }

      this.list.splice(0, this.list.length)
      this.$httpPost('/buss/quarterReward/listPage',
        {
          pageIndex: this.search.pageIndex,
          pageSize: this.search.pageSize,
          endTime: this.search.searchTimes,
          startTime: this.search.searchTime,
        }).then(res => {
          if (res.code === 200) {
            //添加序号&&列表处理
            res.data.content.forEach((item, index) => {
              item.listIndex = index
              // item.actions.ercode={
              //     name: '二维码'
              // }
              // item.occurDate= item.occurDate.substr(0,10)
            })

            this.$publicJs.resetListActions(res.data.content)
            this.$set(this.list, this.list.length, res.data.content)
            this.search.pageSum = parseInt(res.data.totalElements)
          } else {
            this.$messageError(res.data.message)
            this.allowAdd = false;
          }
        }).catch(res => {
          console.log('请求出现错误', res);
          this.$messageError(this.$route.name + '请求失败')
        })

    },
    // 切换列表
    paginationChange(index) {
      this.search.pageIndex = index - 1
      this.getList()
    }
    ,
    // 显示详情弹窗 不同状态
    showDetailDialog(flag, params) {
      console.log(flag, params)
      if (!params) {
        params = {}
      }
      params.contractId = this.contract_id;
      switch (flag) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: 'build',
            typeName: '新增',
            params: params
          }
          break
        case 'update':
          this.postDetailData = {
            show: true,
            type: 'edit',
            typeName: '编辑',
            params: params
          }
          break
        case 'show':
          this.postDetailData = {
            show: true,
            type: 'check',
            typeName: '查看',
            params: params
          }
          break
        case 'history':
          this.postDetailData = {
            show: true,
            type: 'history',
            typeName: '历史',
            params: params
          }
          break
        case 'approve':
          this.postDetailData = {
            show: true,
            type: 'approve',
            typeName: '审批',
            params: params
          }
          break
      }
    },
    //下载文件
    dlFile(e) {
      this.$publicUpload.checkFile(e.id, e.fileName)
    },

    showFiles(row, title) {
      console.log(row, '=============')
      this.fileTitle = title
      this.nowFileList = []
      this.$httpGet(
        `${this.$store.state.httpHost.file}/japi/filesystem/attachment/getFilesByAttach?sys=${this.fileSystem.sys}&module=${this.fileSystem.module}&form=${row.id}`,
      ).then(res => {

        if (res.data.status === 1) {
          this.fileSystem.attachId = res.data.attachid
          let files = []
          if (res.data.attachinfos[0] && res.data.attachinfos[0].part === 'one') {
            files = res.data.attachinfos[0].fileInfo
          }
          files.forEach(item => {
            this.nowFileList.push({
              name: item.name,
              size: item.size,
              link: item.link,
              id: item.id,
              url: this.$store.state.httpHost.file + item.link,
            })
          })
          if (this.nowFileList) {
            this.showFileDialog = true
          }
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        this.$messageError('请求失败!')
      })

    },

    //预览
    viewFile(id) {
      // this.loading = true
      // // file-server/file/preview?id='+id
      // this.$httpGet(
      //     `${this.$store.state.httpHost.file}/file/preview?id=${id}`,
      // ).then(response => {
      //     //  如果是minio地址路径，则调用kkview
      //     if(!response.data.startsWith("/")) {
      //         window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
      //     }else{
      //         //  如果是转换后的previewGetFile，浏览器直接打开
      //         window.open(response.data);
      //     }
      //     this.loading = false
      // })

      this.$httpPost(
        this.$store.state.httpHost.file + `/japi/filesystem/getFilePreview?id=${id}&browserType=1`,
      ).then(res => {
        window.open(res.data.url.replace("/file", this.$store.state.httpHost.file))
        // window.location.href = res.data.url
      }).catch(res => {
        console.log('请求出现错误', res);
      })
    },
    handleSelectionChange(val) {
      this.selectedIds = []
      val.forEach(item => {
        this.selectedIds.push(item.id)
      })
    }
    ,
    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      if (!url.startsWith("http")) {
        url = this.$store.state.httpHost.buss + url;
      }
      this.$httpPost(
        url + query,
        param
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
          // 重新获取数据
          setTimeout(() => {
            this.getList(true)
          }, 1000)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    }
    ,
    // 列表的操作流程
    handleClickDeal(res) {
      let that = this
      let checkProject = res.project
      let type = res.type
      let detailId = res.detailId
      let url = res.url
      let name = res.name
      let actions = res.actions
      console.log(res)
      switch (type) {
        // 二维码
        case 'ercode':
          // 显示详情弹窗
          this.$refs.cmsercode.dialogState();//调用子组件出现弹窗
          // 进行传参
          this.description = checkProject
          this.projectUrl = '/japi/securityTechnicalClarification/getImageList?width=200&height=200&id='
          this.rowId = detailId
          break
        // 修改
        case 'update':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
            actions: actions
          })
          break
        // 查看
        case 'show':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
            actions: actions
          })
          break
        // 上报、重新上报
        case 'report':
          this.$confirm('是否上报?', '提示', {
            confirmButtonClass: 'iconfont icon-icon_ok',
            cancelButtonClass: 'iconfont icon-guanbi',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            this.sealDealHttp(url, `?id=${detailId}`, {}, () => {
              this.$messageSuccess('上报成功!')
            })
          }).catch(() => {
            console.log('请求出现错误',);
          });
          break
        // 撤回上报
        case 'revokeReport':
          this.$prompt('撤回理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            if (value === null || value === '') {
              this.$messageError('请填写撤回理由后重试')
              return
            }
            this.sealDealHttp("/buss/quarterReward/del", `?id=${detailId}&description=${value}`, () => {
              this.$messageSuccess('撤回成功！')
            })
          }).catch(() => {
            console.log('请求出现错误',);
          });
          break
        // 删除
        case 'delete':
          if (detailId === '') {
            this.$messageError('请先选择要删除的记录！')
            return
          }
          this.$confirm('确定是否删除？', '提示', {
            confirmButtonClass: 'iconfont icon-icon_ok',
            cancelButtonClass: 'iconfont icon-guanbi',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            this.$httpPost('/buss/quarterReward/del',
              {
                ids: detailId.split(','),
              }).then(res => {
                if (res.code === 200) {
                  this.$messageSuccess('删除成功！')
                  // 重新获取数据
                  setTimeout(() => {
                    this.getList(true)
                  }, 1000)
                } else {
                  this.$messageError(res.data.message)
                  this.allowAdd = false;
                }
              }).catch(res => {
                console.log('请求出现错误', res);
                this.$messageError(this.$route.name + '请求失败')
              })
          }).catch(() => {
            console.log('请求出现错误',);
          });
          break
        // 同意
        case 'agree':
          // 显示详情弹窗
          this.showDetailDialog('approve', {
            detailId: detailId,
            actions: actions
          })
          break
        // 驳回
        case 'reject':
          this.$prompt('请输入驳回审批意见', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            this.sealDealHttp(url, `?id=${detailId}&description=${value}`, () => {
              this.$messageSuccess('驳回审批成功!')
            })
          }).catch(() => {
            console.log('请求出现错误',);
          });
          break
      }
    }
    ,
  }
}
</script>

<style scoped lang="scss">
</style>
